import React, { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { NavBar, SearchBar, Tag, List, Empty } from 'antd-mobile'

// 搜索数据类型定义
interface SearchResult {
  id: number
  type: 'doctor' | 'hospital' | 'medicine' | 'disease'
  title: string
  subtitle: string
  description: string
  rating?: number
  price?: string
  location?: string
  specialty?: string
  avatar?: string
}

function Index() {
  const navigate = useNavigate()
  const [searchValue, setSearchValue] = useState('')
  const [searchHistory, setSearchHistory] = useState<string[]>([
    '感冒', '发烧', '头痛', '咳嗽'
  ])
  const [hotSearches] = useState<string[]>([
    '高血压', '糖尿病', '心脏病', '胃病', '失眠', '焦虑', '减肥', '营养'
  ])
  const [searchResults, setSearchResults] = useState<SearchResult[]>([])
  const [isSearching, setIsSearching] = useState(false)
  const [hasSearched, setHasSearched] = useState(false)

  // 模拟搜索数据
  const mockSearchData: SearchResult[] = [
    {
      id: 1,
      type: 'doctor',
      title: '张医生',
      subtitle: '内科主任医师',
      description: '擅长治疗感冒、发烧、头痛等常见疾病，有20年临床经验',
      rating: 4.8,
      price: '¥50/次',
      location: '北京协和医院',
      specialty: '内科',
      avatar: '👨‍⚕️'
    },
    {
      id: 2,
      type: 'doctor',
      title: '李医生',
      subtitle: '儿科副主任医师',
      description: '专门治疗儿童感冒、发烧等疾病，深受家长信赖',
      rating: 4.9,
      price: '¥60/次',
      location: '北京儿童医院',
      specialty: '儿科',
      avatar: '👩‍⚕️'
    },
    {
      id: 3,
      type: 'hospital',
      title: '北京协和医院',
      subtitle: '三甲医院',
      description: '全国知名三甲医院，医疗设备先进，专家团队强大',
      rating: 4.7,
      location: '北京市东城区',
      specialty: '综合医院'
    },
    {
      id: 4,
      type: 'medicine',
      title: '感冒灵颗粒',
      subtitle: '感冒用药',
      description: '用于感冒引起的头痛发热，鼻塞流涕等症状',
      price: '¥15.8',
      specialty: '感冒用药'
    },
    {
      id: 5,
      type: 'disease',
      title: '感冒',
      subtitle: '常见疾病',
      description: '感冒是由病毒引起的上呼吸道感染，症状包括发热、咳嗽、流鼻涕等',
      specialty: '呼吸系统疾病'
    }
  ]

  const handleSearch = async (value: string) => {
    if (value.trim()) {
      setIsSearching(true)
      setHasSearched(true)
      
      // 添加到搜索历史
      if (!searchHistory.includes(value)) {
        setSearchHistory(prev => [value, ...prev.slice(0, 9)])
      }
      
      // 模拟搜索延迟
      await new Promise(resolve => setTimeout(resolve, 500))
      
      // 模拟搜索逻辑
      const filteredResults = mockSearchData.filter(item => 
        item.title.toLowerCase().includes(value.toLowerCase()) ||
        item.description.toLowerCase().includes(value.toLowerCase()) ||
        item.specialty?.toLowerCase().includes(value.toLowerCase())
      )
      
      setSearchResults(filteredResults)
      setIsSearching(false)
    }
  }

  // 处理搜索框输入变化
  const handleSearchChange = (value: string) => {
    setSearchValue(value)
    
    // 如果搜索框被清空，返回默认页面
    if (!value.trim()) {
      setHasSearched(false)
      setSearchResults([])
      setIsSearching(false)
    }
  }

  const handleHistoryClick = (item: string) => {
    setSearchValue(item)
    handleSearch(item)
  }

  const handleHotSearchClick = (item: string) => {
    setSearchValue(item)
    handleSearch(item)
  }

  const clearHistory = () => {
    setSearchHistory([])
  }

  // 获取类型图标
  const getTypeIcon = (type: string) => {
    switch (type) {
      case 'doctor': return '👨‍⚕️'
      case 'hospital': return '🏥'
      case 'medicine': return '💊'
      case 'disease': return '🩺'
      default: return '📋'
    }
  }

  // 获取类型标签颜色
  const getTypeColor = (type: string) => {
    switch (type) {
      case 'doctor': return '#1890ff'
      case 'hospital': return '#52c41a'
      case 'medicine': return '#fa8c16'
      case 'disease': return '#722ed1'
      default: return '#666'
    }
  }

  // 处理结果项点击
  const handleResultClick = (result: SearchResult) => {
    switch (result.type) {
      case 'doctor':
        // 跳转到医生详情或聊天页面
        navigate('/message')
        break
      case 'hospital':
        // 跳转到医院详情页面
        console.log('查看医院详情:', result.title)
        break
      case 'medicine':
        // 跳转到药品详情页面
        console.log('查看药品详情:', result.title)
        break
      case 'disease':
        // 跳转到疾病详情页面
        console.log('查看疾病详情:', result.title)
        break
    }
  }

  return (
    <div style={{ backgroundColor: '#f5f5f5', minHeight: '100vh' }}>
      {/* 顶部导航栏 */}
      <NavBar 
        onBack={() => navigate(-1)}
        style={{ 
          backgroundColor: '#fff',
          borderBottom: '1px solid #f0f0f0'
        }}
      >
        搜索
      </NavBar>

      {/* 搜索栏 */}
      <div style={{ 
        backgroundColor: '#fff', 
        padding: '16px',
        borderBottom: '1px solid #f0f0f0'
      }}>
        <SearchBar
          placeholder="搜索医生、医院、药品、疾病症状"
          value={searchValue}
          onChange={handleSearchChange}
          onSearch={handleSearch}
          showCancelButton
          onCancel={() => navigate(-1)}
        />
      </div>

      {/* 搜索历史 */}
      {searchHistory.length > 0 && (
        <div style={{ 
          backgroundColor: '#fff', 
          marginTop: '12px',
          padding: '16px'
        }}>
          <div style={{
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
            marginBottom: '12px'
          }}>
            <span style={{ fontSize: '16px', fontWeight: '600', color: '#333' }}>
              搜索历史
            </span>
            <span 
              onClick={clearHistory}
              style={{ 
                fontSize: '14px', 
                color: '#999',
                cursor: 'pointer'
              }}
            >
              清空
            </span>
          </div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px' }}>
            {searchHistory.map((item, index) => (
              <Tag
                key={index}
                onClick={() => handleHistoryClick(item)}
                style={{
                  backgroundColor: '#f0f0f0',
                  color: '#666',
                  border: 'none',
                  cursor: 'pointer'
                }}
              >
                {item}
              </Tag>
            ))}
          </div>
        </div>
      )}

      {/* 搜索结果显示 */}
      {hasSearched && (
        <div style={{ 
          backgroundColor: '#fff', 
          marginTop: '12px',
          minHeight: '200px'
        }}>
          {isSearching ? (
            <div style={{
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center',
              padding: '40px 20px',
              color: '#666'
            }}>
              搜索中...
            </div>
          ) : searchResults.length > 0 ? (
            <div>
              <div style={{
                padding: '16px 16px 8px 16px',
                fontSize: '16px',
                fontWeight: '600',
                color: '#333',
                borderBottom: '1px solid #f0f0f0'
              }}>
                搜索结果 ({searchResults.length})
              </div>
              <List>
                {searchResults.map((result) => (
                  <List.Item
                    key={result.id}
                    onClick={() => handleResultClick(result)}
                    style={{
                      padding: '16px',
                      cursor: 'pointer'
                    }}
                    prefix={
                      <div style={{
                        fontSize: '24px',
                        marginRight: '12px'
                      }}>
                        {result.avatar || getTypeIcon(result.type)}
                      </div>
                    }
                    title={
                      <div style={{
                        display: 'flex',
                        alignItems: 'center',
                        gap: '8px',
                        marginBottom: '4px'
                      }}>
                        <span style={{
                          fontSize: '16px',
                          fontWeight: '600',
                          color: '#333'
                        }}>
                          {result.title}
                        </span>
                        <span style={{
                          fontSize: '10px',
                          padding: '2px 6px',
                          backgroundColor: getTypeColor(result.type),
                          color: 'white',
                          borderRadius: '8px'
                        }}>
                          {result.type === 'doctor' ? '医生' : 
                           result.type === 'hospital' ? '医院' :
                           result.type === 'medicine' ? '药品' : '疾病'}
                        </span>
                      </div>
                    }
                    description={
                      <div>
                        <div style={{
                          fontSize: '14px',
                          color: '#666',
                          marginBottom: '4px'
                        }}>
                          {result.subtitle}
                        </div>
                        <div style={{
                          fontSize: '12px',
                          color: '#999',
                          lineHeight: '1.4',
                          marginBottom: '8px'
                        }}>
                          {result.description}
                        </div>
                        <div style={{
                          display: 'flex',
                          alignItems: 'center',
                          gap: '12px',
                          fontSize: '12px',
                          color: '#666'
                        }}>
                          {result.rating && (
                            <span>⭐ {result.rating}</span>
                          )}
                          {result.price && (
                            <span style={{ color: '#ff4d4f' }}>{result.price}</span>
                          )}
                          {result.location && (
                            <span>📍 {result.location}</span>
                          )}
                        </div>
                      </div>
                    }
                    arrow={true}
                  />
                ))}
              </List>
            </div>
          ) : (
            <Empty
              description="未找到相关结果"
              image="https://gw.alipayobjects.com/zos/antfincdn/ZHrcdLPrvN/empty.svg"
              style={{
                padding: '40px 20px'
              }}
            />
          )}
        </div>
      )}
      {/* 热门搜索 - 只在未搜索时显示 */}
      {!hasSearched && (
        <div style={{ 
          backgroundColor: '#fff', 
          marginTop: '12px',
          padding: '16px'
        }}>
          <div style={{
            fontSize: '16px',
            fontWeight: '600',
            color: '#333',
            marginBottom: '12px'
          }}>
            热门搜索
          </div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px' }}>
            {hotSearches.map((item, index) => (
              <Tag
                key={index}
                onClick={() => handleHotSearchClick(item)}
                style={{
                  backgroundColor: index < 3 ? '#ff4d4f' : '#f0f0f0',
                  color: index < 3 ? '#fff' : '#666',
                  border: 'none',
                  cursor: 'pointer'
                }}
              >
                {item}
              </Tag>
            ))}
          </div>
        </div>
      )}
    </div>
  )
}

export default Index
